<?php
/**
 * erp近30天销售额报表 (erp)
 */
namespace App\Logic\SalesReport;

use App\Models\Basics\AmazonAccount;
use App\Models\Basics\RakutenAccount;
use App\Models\Basics\ShopifyAccount;
use App\Models\Basics\SysICountry;
use App\Models\Basics\SysPlat;
use App\Models\Basics\SysPlatAccount;
use App\Models\SalesReport\DailySa;
use App\Models\SalesAmazon\SalesAmountDay;
use App\Models\SalesReport\DailySv;
use Illuminate\Support\Facades\DB;
class DailySalesAmount
{

    //销量金额统计报表(erp) (30天)
    public static function init(){

        $amazonPlat = SysPlat::PLAT_AMAZON;
        $shopifuPlat = SysPlat::PLAT_SHOPIFY;
        $rakutenPlat = SysPlat::PLAT_RAKUTEN;
        try{
            $start = date('Ymd',strtotime('-30 days'));
            $end = date('Ymd',strtotime('-1 days'));
            $greaterThan = date('Y-m-d');

            //重置销量额统计报表(近30天销售额)
            DailySa::query()->truncate();

            DB::beginTransaction();
            //amazon
            $i = 0;
            $num = 30;
            $area = [];
            $amazonAccounts = AmazonAccount::optionsForApi();
            while(true){
                if($amazonAccounts->isEmpty())break;
                $_account = $amazonAccounts->splice($i,$num);
                foreach($_account as $__account){
                    $countryIds = SysPlatAccount::getCountriesById($__account->id);
                    foreach ($countryIds as $countryId){
                        $item = SalesAmountDay::query()
                            ->where('plat_id',$amazonPlat)
                            ->where('account_id',$__account->id)
                            ->where('country_id',$countryId)
                            ->whereBetween('day',[$start,$end])
                            ->select('day',DB::raw('sum(amount * rate_odds) as amount'))
                            ->groupBy('day')
                            ->pluck('amount','day')
                            ->toArray();

                        if(!array_key_exists($countryId,$area)){
                            $area[$countryId] = SysICountry::getAreaIdByCountryId($countryId);
                        }
                        $dailySaTotal = [];
                        $dailySaTotal['area_id'] = $area[$countryId];//店铺站点
                        $dailySaTotal['less_than'] = DailySv::SATE_REPORT_DATE;
                        $dailySaTotal['greater_than'] = $greaterThan;
                        $avgSalesAmount = self::getAvgSalesAmount($item);
                        $dailySaTotal = array_merge($dailySaTotal,$avgSalesAmount);
                        DailySa::query()->updateOrCreate([
                            'plat_id' => $amazonPlat,
                            'account_id' => $__account->id,
                            'country_id' => $countryId
                        ],$dailySaTotal);
                    }
                }
            }
            sleep(2);

            //shopify
            $i2 = 0;
            $num2 = 30;
            $shopifyAreaId = 1; //US站点
            $shopifyCountryId = 1; //US国家
            $shopifyAccounts = ShopifyAccount::optionsForApi();
            while(true){
                if($shopifyAccounts->isEmpty())break;
                $_account = $shopifyAccounts->splice($i2,$num2);
                foreach($_account as $__account){
                    $item = SalesAmountDay::query()
                        ->where('plat_id',$shopifuPlat)
                        ->where('account_id',$__account->id)
                        //->where('country_id',$countryId)
                        ->whereBetween('day',[$start,$end])
                        ->select('day',DB::raw('sum(amount * rate_odds) as amount'))
                        ->groupBy('day')
                        ->pluck('amount','day')
                        ->toArray();

                    $dailySaTotal = [];
                    $dailySaTotal['area_id'] = $shopifyAreaId;
                    $dailySaTotal['less_than'] = DailySv::SATE_REPORT_DATE;
                    $dailySaTotal['greater_than'] = $greaterThan;
                    $avgSalesAmount = self::getAvgSalesAmount($item);
                    $dailySaTotal = array_merge($dailySaTotal,$avgSalesAmount);
                    DailySa::query()->updateOrCreate([
                        'plat_id' => $shopifuPlat,
                        'account_id' => $__account->id,
                        'country_id' => $shopifyCountryId
                    ],$dailySaTotal);
                }
            }
            sleep(2);

            //rakuten
            $i3 = 0;
            $num3 = 30;
            $rakutenAreaId = 6; //JP站点
            $rakutenCountryId = 12; //JP国家
            $rakutenAccounts = RakutenAccount::optionsForApi();
            while(true){
                if($rakutenAccounts->isEmpty())break;
                $_account = $rakutenAccounts->splice($i3,$num3);
                foreach($_account as $__account){
                    $item = SalesAmountDay::query()
                        ->where('plat_id',$rakutenPlat)
                        ->where('account_id',$__account->id)
                        //->where('country_id',$countryId)
                        ->whereBetween('day',[$start,$end])
                        ->select('day',DB::raw('sum(amount * rate_odds) as amount'))
                        ->groupBy('day')
                        ->pluck('amount','day')
                        ->toArray();

                    $dailySaTotal = [];
                    $dailySaTotal['area_id'] = $rakutenAreaId;
                    $dailySaTotal['less_than'] = DailySv::SATE_REPORT_DATE;
                    $dailySaTotal['greater_than'] = $greaterThan;
                    $avgSalesAmount = self::getAvgSalesAmount($item);
                    $dailySaTotal = array_merge($dailySaTotal,$avgSalesAmount);
                    DailySa::query()->updateOrCreate([
                        'plat_id' => $rakutenPlat,
                        'account_id' => $__account->id,
                        'country_id' => $rakutenCountryId
                    ],$dailySaTotal);
                }
            }
            sleep(2);

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * 销售额
     * @param $item
     * @return array
     */
    protected static function getAvgSalesAmount($item){
        $re = [];
        $sum3 = 0;
        $sum7 = 0;
        $sum15 = 0;
        $sum30 = 0;
        $count = 0;
        for($i = 30;$i >= 1;$i--){
            $count++;
            $date = date('Ymd',strtotime("-{$i} days"));
            $amount = array_key_exists($date,$item) ? floatval($item[$date]) : 0;
            if($count > 27){
                $sum3 += $amount;
            }
            if($count > 23){
                $sum7 += $amount;
            }
            if($count > 15){
                $sum15 += $amount;
            }
            $sum30 += $amount;
        }
        $re['avg3'] = round($sum3 / 3,2);
        $re['avg7'] = round($sum7 / 7,2);
        $re['avg15'] = round($sum15 / 15,2);
        $re['avg30'] = round($sum30 / 30,2);
        $re['sales_status'] = DailySv::getSalesStatus($re['avg3'],$re['avg7'],$re['avg15'],$re['avg30']);
        $re['avg'] = DailySv::getWeightAvg($re['avg3'],$re['avg7'],$re['avg15'],$re['avg30'],$re['sales_status']);
        return $re;
    }
}
